package com.bigshen.algorithm.cQueue.solution02RecommendedResults;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Recommended Results Are Scattered
 * 推荐结果打散
 *
 *  给定一串视频和图片广告的集合，规定 n个视频后跟一个广告图片，在此基础上重组数据
 *  e.g  最少3个视频后才能跟一个广告
 *  v_0,v_1,v_2,v_3,v_4,p5,p6,p7,p8,v_9,v_10
 *
 *   打散之后： v_0,v_1,v_2,p5, v_3,v_4,v_9,p6, v_10 后面p用不完自动舍弃
 */
public class Solution {

    public static void main(String[] args) {
        List<String> picAndVideoList = new ArrayList<>();

//        picAndVideoList.add("p_01");
//        picAndVideoList.add("p_02");
//        picAndVideoList.add("p_03");
        picAndVideoList.add("v_1");
        picAndVideoList.add("v_2");
        picAndVideoList.add("p_04");
        picAndVideoList.add("p_05");
        picAndVideoList.add("v_6");
        picAndVideoList.add("p_07");
        picAndVideoList.add("v_8");
        picAndVideoList.add("v_9");
        List<String> result = new Solution().getRecommendedResult(picAndVideoList, 2);
        for (int i = 0; i < result.size(); i++) {
            System.out.println(result.get(i));
        }
    }

    public List<String> getRecommendedResult(List<String> picAndVideo, int maxInterval) {

        List<String> result = new ArrayList<>();
        if (null == picAndVideo || picAndVideo.size() == 0) {
            return result;
        }

        int index = 0;
        Queue<String> picQueue = new LinkedList<>();
        for (String element : picAndVideo) {
            if (isVideo(element)) {
                // 如果是video
                result.add(element);
                index++;
                if (index >= maxInterval && !picQueue.isEmpty()) {
                    // 已满足推荐区间，插入
                    result.add(picQueue.poll());
                    index = 0;
                }
            } else {
                // 已满足插入广告图片条件，不用入队，直接插入
                if (index >= maxInterval) {
                    result.add(element);
                    index = 0;
                } else {
                    // 不满足插入条件，入队等待
                    picQueue.add(element);
                }
            }
        }

        return result;
    }

    private boolean isVideo(String element) {
        return element.startsWith("v_");
    }


}
